package docsim;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import org.apache.hadoop.io.WritableComparable;

public class DocumentCountMap implements WritableComparable{
	ArrayList<DocumentCount> list = new ArrayList<DocumentCount>();

	public void add(DocumentCount dc) {
		list.add(dc);
	}

	@Override
	public void readFields(DataInput arg0) throws IOException {
		int len = arg0.readInt();
		DocumentCount dc = new DocumentCount();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(dc);
		byte[] b = bos.toByteArray();
		for(int i = 0; i<len; i++)
		{
			arg0.readFully(b);
			ByteArrayInputStream bis = new ByteArrayInputStream(b);
			ObjectInputStream ois = new ObjectInputStream(bis);
			try {
				DocumentCount inObject = (DocumentCount) ois.readObject();
				list.add(inObject);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void write(DataOutput arg0) throws IOException {
		arg0.writeInt(list.size());
		for(int i = 0; i <list.size(); i++)
		{
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(list.get(i));
			byte[] b = bos.toByteArray();
			arg0.write(b);
		}
	}

	@Override
	public int compareTo(Object o) {
		if(((DocumentCountMap)o).list.size() != list.size())
		{
			return (((DocumentCountMap)o).list.size() - list.size());
		}
		else
		{
			for(int i = 0;i<list.size();i++)
			{
				if(((DocumentCountMap)o).list.get(i) != list.get(i))
				{
					return -1;
				}
			}
			return 0;
		}
	}
	
	@Override
	public int hashCode() {
		int hash = list.get(0).hashCode();
		for(int i = 1;i<list.size();i++)
		{
			hash = (31*hash) ^ list.get(i).hashCode();
		}
		return hash;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof DocumentCountMap)
		{
			for(int i = 0;i<list.size();i++)
			{
				if(((DocumentCountMap)obj).list.get(i) != list.get(i))
				{
					return false;
				}
			}
			return true;
		}
		else
		{
			return false;
		}
	}
}